package com.heima.wemedia.filter;

import com.heima.model.media.pojos.WmUser;
import com.heima.wemedia.utils.ThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.core.config.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(1) // 加载顺序
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Log4j2
public class WmTokenFilter extends GenericFilterBean {
    // 给链上添加wmUser对象,让后续的所有方法共享改变量
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 从请求中获取数据
        String userId = request.getHeader("userId");
        if (userId!=null){
            WmUser wmUser=new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            ThreadLocalUtils.setUser(wmUser);
        }

        //放行请求
        filterChain.doFilter(request,response);
    }
}
